<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 6.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha256-Z1K5uhUaJXA7Ll0XrZ/0JhX4lAtZFpT6jkKrEDT0drU=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.14.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":-1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="读写文件相关write 头文件: 1#include &lt;unistd.h&gt;  函数说明:write系统调用，是把缓存区buf中的前nbytes字节写入到与文件描述符有关的文件中。  函数定义 12&#x2F;&#x2F;参数分别为 文件描述符、缓冲区、size_t write(int flides, const void *buf, size_t nbytes);  返回值write系统调用返回的是实际写">
<meta property="og:type" content="article">
<meta property="og:title" content="Linux读写文件相关库函数">
<meta property="og:url" content="http://example.com/2021/11/20/Linux%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E7%9B%B8%E5%85%B3%E5%BA%93%E5%87%BD%E6%95%B0/index.html">
<meta property="og:site_name" content="JsyBlog">
<meta property="og:description" content="读写文件相关write 头文件: 1#include &lt;unistd.h&gt;  函数说明:write系统调用，是把缓存区buf中的前nbytes字节写入到与文件描述符有关的文件中。  函数定义 12&#x2F;&#x2F;参数分别为 文件描述符、缓冲区、size_t write(int flides, const void *buf, size_t nbytes);  返回值write系统调用返回的是实际写">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-11-20T14:07:03.000Z">
<meta property="article:modified_time" content="2022-03-28T07:28:00.275Z">
<meta property="article:author" content="SongyangJi">
<meta property="article:tag" content="C">
<meta property="article:tag" content="Linux">
<meta property="article:tag" content="File">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="http://example.com/2021/11/20/Linux%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E7%9B%B8%E5%85%B3%E5%BA%93%E5%87%BD%E6%95%B0/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://example.com/2021/11/20/Linux%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E7%9B%B8%E5%85%B3%E5%BA%93%E5%87%BD%E6%95%B0/","path":"2021/11/20/Linux读写文件相关库函数/","title":"Linux读写文件相关库函数"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>Linux读写文件相关库函数 | JsyBlog</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">JsyBlog</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E7%9B%B8%E5%85%B3"><span class="nav-number">1.</span> <span class="nav-text">读写文件相关</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#write"><span class="nav-number">1.1.</span> <span class="nav-text">write</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#read"><span class="nav-number">1.2.</span> <span class="nav-text">read</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#open"><span class="nav-number">1.3.</span> <span class="nav-text">open</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#close"><span class="nav-number">1.4.</span> <span class="nav-text">close</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fopen"><span class="nav-number">1.5.</span> <span class="nav-text">fopen</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fclose"><span class="nav-number">1.6.</span> <span class="nav-text">fclose</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#fprintf"><span class="nav-number">1.7.</span> <span class="nav-text">fprintf</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#flock"><span class="nav-number">1.8.</span> <span class="nav-text">flock</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#snprintf"><span class="nav-number">1.9.</span> <span class="nav-text">snprintf</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E9%87%8D%E5%AE%9A%E5%90%91"><span class="nav-number">2.</span> <span class="nav-text">重定向</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#dup"><span class="nav-number">2.1.</span> <span class="nav-text">dup</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#dup2"><span class="nav-number">2.2.</span> <span class="nav-text">dup2</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">SongyangJi</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">251</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">45</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">109</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/11/20/Linux%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6%E7%9B%B8%E5%85%B3%E5%BA%93%E5%87%BD%E6%95%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="SongyangJi">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="JsyBlog">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="Linux读写文件相关库函数 | JsyBlog">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Linux读写文件相关库函数
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2021-11-20 22:07:03" itemprop="dateCreated datePublished" datetime="2021-11-20T22:07:03+08:00">2021-11-20</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2022-03-28 15:28:00" itemprop="dateModified" datetime="2022-03-28T15:28:00+08:00">2022-03-28</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/Linux/" itemprop="url" rel="index"><span itemprop="name">Linux</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="读写文件相关"><a href="#读写文件相关" class="headerlink" title="读写文件相关"></a>读写文件相关</h2><h3 id="write"><a href="#write" class="headerlink" title="write"></a>write</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>write系统调用，是把缓存区buf中的前nbytes字节写入到与文件描述符有关的文件中。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数分别为 文件描述符、缓冲区、</span></span><br><span class="line"><span class="type">size_t</span> <span class="title function_">write</span><span class="params">(<span class="type">int</span> flides, <span class="type">const</span> <span class="type">void</span> *buf, <span class="type">size_t</span> nbytes)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>write系统调用返回的是实际写入到文件中的字节数。</p>
</li>
</ul>
<h3 id="read"><a href="#read" class="headerlink" title="read"></a>read</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>read系统调用，是从与文件描述符flides相关联的文件中读取前nbytes字节的内容，并且写入到数据区buf中。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">size_t</span> <span class="title function_">read</span><span class="params">(<span class="type">int</span> flides, <span class="type">void</span> *buf, <span class="type">size_t</span> nbytes)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>read系统调用返回的是实际读入的字节数。</p>
</li>
</ul>
<h3 id="open"><a href="#open" class="headerlink" title="open"></a>open</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/stat.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">open</span><span class="params">(<span class="type">const</span> *path, <span class="type">int</span> oflags)</span>; <span class="comment">//1</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">open</span><span class="params">(<span class="type">const</span> *path, <span class="type">int</span> oflags, <span class="type">mode_t</span> mode)</span>; <span class="comment">//2</span></span><br></pre></td></tr></table></figure></li>
</ul>
<p>参数说明：<br>其中，oflags是由必需文件访问模式和可选模式一起构成的(通过按位或“|”)：<br>必需部分：</p>
<ul>
<li>O_RDONLY———-以只读方式打开</li>
<li>O_WRONLY———以只写方式打开</li>
<li>O_RDWR————以读写方式打开<br>可选部分：</li>
<li>O_CREAT————按照参数mode给出的访问模式创建文件</li>
<li>O_EXCL————–与O_CREAT一起使用，确保创建出文件，避免两个程序同时创建同一个文件，如文件存在则open调用失败 </li>
<li>O_APPEND———-把写入数据追加在文件的末尾</li>
<li>O_TRUNC———–把文件长度设置为0，丢弃原有内容</li>
</ul>
<p>在第一种调用方式上，加上了第三个参数mode，<strong>主要是搭配O_CREAT使用</strong>，同样地，这个参数规定了属主、同组和其他人对文件的文件操作权限。</p>
<ul>
<li>文件属主<ul>
<li>S_IRUSR———-读权限 </li>
<li>S_IWUSR———写权限</li>
<li>S_IXUSR———-执行权限</li>
</ul>
</li>
<li>文件所属组  <ul>
<li>S_IRGRP———-读权限 </li>
<li>S_IWGRP———写权限 </li>
<li>S_IXGRP———-执行权限</li>
</ul>
</li>
<li>其他人  <ul>
<li>S_IROTH———-读权限 </li>
<li>S_IWOTH———写权限</li>
<li>S_IXOTH———-执行权限</li>
</ul>
</li>
</ul>
<p>另外，也可以用数字设定法：<br>0 : 无权限；<br>1 : 只执行；<br>2 : 只写；<br>4 : 只读。</p>
<p>这种权限设计实际上就是linux文件权限的设计。</p>
<ul>
<li>返回值<br>open系统调用成功返回一个新的文件描述符，失败返回-1。</li>
</ul>
<h3 id="close"><a href="#close" class="headerlink" title="close"></a>close</h3><ul>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">close</span><span class="params">(<span class="type">int</span> flides)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>终止文件描述符flides与其对应的文件间的联系，文件描述符被释放，可重新使用。<br>使用完文件描述符之后，要记得释放！</p>
</li>
</ul>
<h3 id="fopen"><a href="#fopen" class="headerlink" title="fopen"></a>fopen</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br></pre></td></tr></table></figure></li>
<li><p>函数说明:<br>C 库函数,使用给定的模式 mode 打开 filename 所指向的文件。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">FILE *<span class="title function_">fopen</span><span class="params">(<span class="type">const</span> <span class="type">char</span> *filename, <span class="type">const</span> <span class="type">char</span> *mode)</span></span><br></pre></td></tr></table></figure>
<table>
<thead>
<tr>
<th>“r”</th>
<th>打开一个用于读取的文件。该文件必须存在。</th>
</tr>
</thead>
<tbody><tr>
<td>“w”</td>
<td>创建一个用于写入的空文件。如果文件名称与已存在的文件相同，则会删除已有文件的内容，文件被视为一个新的空文件。</td>
</tr>
<tr>
<td>“a”</td>
<td>追加到一个文件。写操作向文件末尾追加数据。如果文件不存在，则创建文件。</td>
</tr>
<tr>
<td>“r+”</td>
<td>打开一个用于更新的文件，可读取也可写入。该文件必须存在。</td>
</tr>
<tr>
<td>“w+”</td>
<td>创建一个用于读写的空文件。</td>
</tr>
<tr>
<td>“a+”</td>
<td>打开一个用于读取和追加的文件。</td>
</tr>
</tbody></table>
</li>
<li><p>返回值<br>该函数返回一个 FILE 指针。否则返回 NULL，且设置全局变量 errno 来标识错误。</p>
</li>
</ul>
<h3 id="fclose"><a href="#fclose" class="headerlink" title="fclose"></a>fclose</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br></pre></td></tr></table></figure></li>
<li><p>函数说明:<br>C 库函数 int fclose(FILE *stream) 关闭流 stream, 并且刷新所有的缓冲区。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// stream -- 这是指向 FILE 对象的指针，该 FILE 对象指定了要被关闭的流。</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">fclose</span><span class="params">(FILE *stream)</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>如果流成功关闭，则该方法返回零。如果失败，则返回 EOF。</p>
</li>
</ul>
<h3 id="fprintf"><a href="#fprintf" class="headerlink" title="fprintf"></a>fprintf</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br></pre></td></tr></table></figure></li>
<li><p>函数说明:<br>C 库函数, 发送格式化输出到流 stream 中。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">fprintf</span><span class="params">(FILE *stream, <span class="type">const</span> <span class="type">char</span> *format, ...)</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>如果成功，则返回写入的字符总数，否则返回一个负数。</p>
</li>
</ul>
<h3 id="flock"><a href="#flock" class="headerlink" title="flock"></a>flock</h3><ul>
<li><p>头文件 </p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/file.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明 flock()会依参数operation所指定的方式对参数fd所指的文件做各种锁定或解除锁定的动作。<br>此函数只能锁定整个文件，无法锁定文件的某一区域。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// fd 文件描述符、 锁定operation</span></span><br><span class="line"><span class="type">int</span> <span class="title function_">flock</span><span class="params">(<span class="type">int</span> fd,<span class="type">int</span> operation)</span>;</span><br></pre></td></tr></table></figure></li>
</ul>
<p>参数 operation 有下列四种情况:</p>
<ul>
<li>LOCK_SH 建立共享锁定。多个进程可同时对同一个文件作共享锁定。</li>
<li>LOCK_EX 建立互斥锁定。一个文件同时只有一个互斥锁定。</li>
<li>LOCK_UN 解除文件锁定状态。</li>
<li>LOCK_NB 无法建立锁定时，此操作可不被阻断，马上返回进程。(通常与LOCK_SH或LOCK_EX做OR组合)</li>
</ul>
<ul>
<li>返回值<br>返回0表示成功，若有错误则返回-1，错误代码存于errno。</li>
</ul>
<h3 id="snprintf"><a href="#snprintf" class="headerlink" title="snprintf"></a>snprintf</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>C 库函数，将可变参数(…)按照 format 格式化成字符串，并将字符串复制到 str 中，size 为要写入的字符的最大数目，超过 size 会被截断。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">snprintf</span> <span class="params">(<span class="type">char</span> * str, <span class="type">size_t</span> size, <span class="type">const</span> <span class="type">char</span> * format, ... )</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>str – 目标字符串。</li>
<li>size – 拷贝字节数(Bytes)。</li>
<li>format – 格式化成字符串。</li>
<li>… – 可变参数。</li>
</ul>
</li>
<li><p>返回值</p>
<ul>
<li>如果格式化后的字符串长度小于等于 size，则会把字符串全部复制到 str 中，并给其后添加一个字符串结束符 \0。<br>返回的实际写入的长度。</li>
<li>如果格式化后的字符串长度大于 size，超过 size 的部分会被截断，只将其中的 (size-1) 个字符复制到 str 中，并给其后添加一个字符串结束符 \0。<br>返回值为欲写入的字符串长度。</li>
</ul>
</li>
</ul>
<h2 id="重定向"><a href="#重定向" class="headerlink" title="重定向"></a>重定向</h2><h3 id="dup"><a href="#dup" class="headerlink" title="dup"></a>dup</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>dup用来复制参数oldfd所指的文件描述符。<br>返回的新文件描述符和参数oldfd指向同一个文件，这<strong>两个描述符共享同一个数据结构，共享所有的锁定，读写指针和各项标志位</strong>。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">dup</span><span class="params">(<span class="type">int</span> oldfd)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>当复制成功是，返回最小的尚未被使用过的文件描述符;<br>若有错误则返回-1。<br>错误代码存入errno中。</p>
</li>
</ul>
<h3 id="dup2"><a href="#dup2" class="headerlink" title="dup2"></a>dup2</h3><ul>
<li><p>头文件:</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br></pre></td></tr></table></figure>
</li>
<li><p>函数说明:<br>dup2与dup区别是dup2可以用参数newfd指定新文件描述符的数值。<br>若参数newfd已经被程序使用，则系统就会将newfd所指的文件关闭；<br>若newfd等于oldfd，则返回newfd,而不关闭newfd所指的文件。<br>dup2所复制的文件描述符与原来的文件描述符共享各种文件状态。共享所有的锁定，读写位置和各项权限或flags等.<br>在shell的重定向功能中，(输入重定向”&lt;”和输出重定向”&gt;”)就是通过调用dup或dup2函数对标准输入和标准输出的操作来实现的。</p>
</li>
<li><p>函数定义</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="type">int</span> <span class="title function_">dup2</span><span class="params">(<span class="type">int</span> oldfd, <span class="type">int</span> newfd)</span>;</span><br></pre></td></tr></table></figure>
</li>
<li><p>返回值<br>若dup2调用成功则返回新的文件描述符，出错则返回-1。</p>
</li>
<li><p>举例：<br>如何使用dup2实现标准输出到文件的重定向？</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span><span class="string">&lt;string.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">()</span> &#123;</span><br><span class="line">    <span class="type">int</span> oldfd;</span><br><span class="line">    <span class="type">int</span> fd;</span><br><span class="line">    <span class="type">int</span> t;</span><br><span class="line">    <span class="type">char</span> *buf = <span class="string">&quot;This is a test!!!!\n&quot;</span>;</span><br><span class="line">    <span class="keyword">if</span> ((oldfd = open(<span class="string">&quot;/Users/jisongyang/CLionProjects/test_syscalls_sandbox/redirect/mine.txt&quot;</span>, O_RDWR | O_CREAT,</span><br><span class="line">                      <span class="number">0644</span>)) == <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;open error\n&quot;</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    fd = dup2(oldfd, STDOUT_FILENO);</span><br><span class="line">    <span class="keyword">if</span> (fd == <span class="number">-1</span>) &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;dup2 error\n&quot;</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;fd:%d  STDOUT_FILENO:%d\n&quot;</span>, fd, STDOUT_FILENO);</span><br><span class="line">    &#125;</span><br><span class="line">    t = (<span class="type">int</span>) <span class="built_in">strlen</span>(buf);</span><br><span class="line">    <span class="keyword">if</span> (write(fileno(<span class="built_in">stdout</span>), buf, t) != t)<span class="comment">//本应该写入到stdout的信息，但是标准输出已经重定向到目标文件中，故向标准输出写的数据将会写到目标文件中。</span></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">printf</span>(<span class="string">&quot;write error!\n&quot;</span>);</span><br><span class="line">        <span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    fflush(<span class="built_in">stdout</span>); <span class="comment">// printf 是带缓冲的函数，不加这一行代码，printf 的内容不会写到文件里</span></span><br><span class="line">    close(fd);</span><br><span class="line">    <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
<p>最重要的一行代码：<code>dup2(oldfd, STDOUT_FILENO)</code></p>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/C/" rel="tag"># C</a>
              <a href="/tags/Linux/" rel="tag"># Linux</a>
              <a href="/tags/File/" rel="tag"># File</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/11/20/socket/" rel="prev" title="Socket编程 —— 使用 select、poll、epoll">
                  <i class="fa fa-chevron-left"></i> Socket编程 —— 使用 select、poll、epoll
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2021/11/20/Linux%E6%97%B6%E9%97%B4%E7%9B%B8%E5%85%B3%E5%BA%93%E5%87%BD%E6%95%B0/" rel="next" title="Linux时间相关库函数">
                  Linux时间相关库函数 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">SongyangJi</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>





  





</body>
</html>
